trigger UpdateAuditPlan on Audit_Plan__c (after update) {
    if(trigger.isUpdate)
    {
        List<Id> AuditPlanIds = new List<Id>();
        Integer num = 0;
        
        for(Audit_Plan__c ad : trigger.new)
        {
            List<Audit_Plan__c> newAuditPlan = [Select id,Audit_Date__c From Audit_Plan__c Where Audit_Date__c =: ad.Audit_Date__c and ownerid =: ad.ownerid];
            if(newAuditPlan.size() > 1)
                ad.addError(ad.Audit_Date__c + '审计计划已存在！不能转到这天');
            else
            {           
                 List<Event>EventList = [Select StartDateTime, EndDateTime,id From Event Where ownerid =: ad.ownerid  and EVENTDATE__C =: ad.Audit_Date__c ];
                
                for(Event e : EventList )
                {
                    ad.addError('aa');
                    e.StartDateTime = e.StartDateTime.addDays(trigger.old[num].Audit_Date__c.daysBetween(ad.Audit_Date__c));
                    e.EndDateTime = e.StartDateTime.addDays(trigger.old[num].Audit_Date__c.daysBetween(ad.Audit_Date__c));
                }
                update EventList;
                
                List<Audit__c> AuditPlan = [Select End_Date__c,Start_Date__c,Plan_Date__c,id From Audit__c Where Audit_Plan__c =: ad.id];
                List<Audit__c> UpdateAudit = new List<Audit__c>();
                for(Audit__c e : AuditPlan)
                {
                    e.Plan_Date__c = ad.Audit_Date__c;
                    UpdateAudit.add(e);
                }
                update UpdateAudit;
                num++;
            }
        }


    }

}